//
//  ConfigMgr.m
//  carcareIOS
//
//  Created by ileo on 16/7/27.
//  Copyright © 2016年 chezheng. All rights reserved.
//

#import "ConfigMgr.h"
#import "JsonExtend.h"
#import "NSString+Encode.h"
#import "EncryptMgr.h"
#import "JPEngine.h"




#define URL_HEAD @"http://r.ichezheng.com/download/cz"

#define CODE @"3a06ca92e95705e1"

#define TIMEOUT 5



@implementation ConfigMgr

+(void)newVersionInfo:(void (^)(NSDictionary *))finish{
    [self requestWithURLPath:[self pathWithName:@"/iOS/newVersion"] finish:^(NSDictionary *dic) {
        if (finish && [dic[@"newVersion"] compare:__APP_V options:NSNumericSearch] == NSOrderedDescending) {
            finish(dic);
        }
    }];
}

+(void)jsPatchFixBug{
    [self requestWithURLPath:[self pathWithName:[NSString stringWithFormat:@"/iOS/fixBug-%@",__APP_V]] finish:^(NSDictionary *dic) {
        if ([[EncryptMgr encryptWithString:dic[@"fixCode"]] isEqualToString:dic[@"verify"]]) {
            [JPEngine startEngine];
            [JPEngine evaluateScript:dic[@"fixCode"]];
        }
    }];
}

+(void)requestWithURLPath:(NSString *)path finish:(void (^)(NSDictionary *dic))finish{
    [[[NSURLSession sharedSession] dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:TIMEOUT] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSDictionary *dic = [NSDictionary dictionaryWithJsonValue:json];
        if (dic && finish) {
            finish(dic);
        }
    }] resume];
}

+(NSString *)pathWithName:(NSString *)name{
    return [NSString stringWithFormat:@"%@%@",URL_HEAD,name];
}



@end
